import { useState, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { Button, Calendar, Card, Toast } from 'antd-mobile'
import { LeftOutline, CalendarOutline, ClockCircleOutline, UserOutline } from 'antd-mobile-icons'
import { type Training } from '../../services/dataService'
import './schedule-training.css'

interface TimeSlot {
  id: string
  time: string
  available: boolean
}

const ScheduleTraining = () => {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const trainingId = searchParams.get('id')
  
  const [selectedDate, setSelectedDate] = useState<Date>(new Date())
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('')
  const [training, setTraining] = useState<Training | null>(null)

  // 初始化数据（从后端 MySQL trainings 表获取）
  useEffect(() => {
    const load = async () => {
      if (!trainingId) return
      try {
        // 优先按 REST 习惯请求 /api/trainings/:id
        const res = await fetch(`/api/trainings/${trainingId}`)
        if (res.ok) {
          const data = await res.json()
          setTraining(data as unknown as Training)
          return
        }
        // 兼容没有按 id 路由的情况：拉取列表后再本地查找
        const res2 = await fetch(`/api/trainings`)
        if (res2.ok) {
          const list = (await res2.json()) as Training[]
          const t = list.find((i) => String(i.id) === String(trainingId)) || null
          setTraining(t)
        }
      } catch (err) {
        console.error('加载训练详情失败:', err)
      }
    }
    load()
  }, [trainingId])

  // 可用时间段
  const timeSlots: TimeSlot[] = [
    { id: '1', time: '08:00', available: true },
    { id: '2', time: '09:00', available: true },
    { id: '3', time: '10:00', available: false },
    { id: '4', time: '11:00', available: true },
    { id: '5', time: '14:00', available: true },
    { id: '6', time: '15:00', available: true },
    { id: '7', time: '16:00', available: false },
    { id: '8', time: '17:00', available: true },
    { id: '9', time: '18:00', available: true },
    { id: '10', time: '19:00', available: true }
  ]

  const handleDateSelect = (date: Date | null) => {
    if (date) {
      setSelectedDate(date)
      setSelectedTimeSlot('') // 重置时间选择
    }
  }

  const handleTimeSlotSelect = (slotId: string) => {
    setSelectedTimeSlot(slotId)
  }

  const handleConfirmBooking = () => {
    if (!selectedTimeSlot) {
      Toast.show('请选择训练时间')
      return
    }

    const selectedSlot = timeSlots.find(slot => slot.id === selectedTimeSlot)
    if (!selectedSlot) return

    // 这里可以调用API保存预定信息
    Toast.show({
      content: `预定成功！${selectedDate.toLocaleDateString()} ${selectedSlot.time}`,
      duration: 2000
    })

    // 延迟跳转回训练详情页
    setTimeout(() => {
      navigate(-1)
    }, 2000)
  }

  const formatDate = (date: Date) => {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      weekday: 'long'
    })
  }

  if (!training) {
    return (
      <div className="schedule-page">
        <div className="schedule-header">
          <button className="back-btn" onClick={() => navigate(-1)}>
            <LeftOutline />
          </button>
          <div className="title">预定训练</div>
          <div style={{ width: 24 }} />
        </div>
        <div className="loading">加载中...</div>
      </div>
    )
  }

  return (
    <div className="schedule-page">
      {/* 顶部导航 */}
      <div className="schedule-header">
        <button className="back-btn" onClick={() => navigate(-1)}>
          <LeftOutline />
        </button>
        <div className="title">预定训练</div>
        <div style={{ width: 24 }} />
      </div>

      <div className="schedule-content">
        {/* 训练信息卡片 */}
        <Card className="training-info-card">
          <div className="training-info">
            <img src={training.cover} alt={training.title} className="training-cover" />
            <div className="training-details">
              <h3 className="training-title">{training.title}</h3>
              <div className="training-meta">
                <div className="meta-item">
                  <ClockCircleOutline />
                  <span>{training.duration}</span>
                </div>
                <div className="meta-item">
                  <UserOutline />
                  <span>{training.level}</span>
                </div>
              </div>
            </div>
          </div>
        </Card>

        {/* 日期选择 */}
        <div className="date-section">
          <div className="section-title">
            <CalendarOutline />
            <span>选择日期</span>
          </div>
          <Card className="calendar-card">
            <Calendar
              value={selectedDate}
              onChange={handleDateSelect}
              selectionMode="single"
            />
          </Card>
        </div>

        {/* 选中日期显示 */}
        <div className="selected-date">
          <div className="date-display">
            <CalendarOutline />
            <span>{formatDate(selectedDate)}</span>
          </div>
        </div>

        {/* 时间段选择 */}
        <div className="time-section">
          <div className="section-title">
            <ClockCircleOutline />
            <span>选择时间</span>
          </div>
          <div className="time-slots-grid">
            {timeSlots.map((slot) => (
              <button
                key={slot.id}
                className={`time-slot ${!slot.available ? 'unavailable' : ''} ${
                  selectedTimeSlot === slot.id ? 'selected' : ''
                }`}
                onClick={() => slot.available && handleTimeSlotSelect(slot.id)}
                disabled={!slot.available}
              >
                {slot.time}
                {!slot.available && <span className="unavailable-text">已满</span>}
              </button>
            ))}
          </div>
        </div>

        {/* 确认预定按钮 */}
        <div className="booking-actions">
          <Button
            color="primary"
            size="large"
            block
            onClick={handleConfirmBooking}
            disabled={!selectedTimeSlot}
            style={{
              background: selectedTimeSlot ? '#ff6b35' : '#ccc',
              border: 'none',
              borderRadius: '25px',
              height: '50px',
              fontSize: '16px',
              fontWeight: 'bold'
            }}
          >
            确认预定
          </Button>
        </div>
      </div>
    </div>
  )
}

export default ScheduleTraining
